'use strict';
const {
	log
} = require('console');
// 通过 require 引入 vk 实例
const vk = require('vk-unicloud');
// 通过 vk.init 初始化 vk实例（只有初始化后才能使用）
vk.init({
	baseDir: __dirname,
	requireFn: require
});

exports.main = async (event, context) => {
	const db = uniCloud.database();
	const _ = db.command;
	//event为客户端上传的参数
	console.log('为客户端上传的参数 : ', event)
	//为防止伪造，验证签名signature，如果和返回值里的event.body.signature一致，校验通过
	let token = "80a11a4f738c69b68e25e568f5660572247a036c";
	let parms = JSON.parse(event.body)

	console.log('event为客户端上传的参数', parms)


	let msg = parms.msg;
	let nonce = parms.nonce;
	let timestamp = parms.timestamp;
	let msg_signature = parms.msg_signature;
	var userInfo = {};
	var nowtime = new Date().getTime();

	const strArr = [token, timestamp, nonce, msg].sort();
	const str = strArr.join('');
	const _signature = require('crypto').createHash('sha1').update(str).digest('hex');

	const parms_msg = JSON.parse(parms.msg)

	//如果签名失败，则直接返回
	if (msg_signature != _signature) {
		console.log("签名校验失败");
		let res = {
			"err_no": 1,
			"err_tips": "fail"
		}
		return res
	}

	//如果算出来的签名和支付系统返回的签名一致，说明请求来源正常
	console.log("签名一致，校验成功");

	console.log("hhhhhhh", );
	const order_temp = await db.collection('a_recharge').where({
		out_trade_no: parms_msg.cp_orderno
	}).get()
	const orderinfo = order_temp.data[0]

	if (orderinfo.subject == "充值金豆" && orderinfo.pay_status == 0) {
		//如果修改成功，给用户增加金豆数量

		// const newInfo = await db.collection('uni-id-users').doc(orderinfo.user_id).updateAndReturn({
		// 	balance: _.inc(orderinfo.bean)
		// })


		let newInfo = await vk.baseDao.updateAndReturn({
			dbName: "uni-id-users",
			whereJson: {
				_id: orderinfo.user_id
			},
			dataJson: {
				balance: _.inc(orderinfo.bean)
			}
		});


		console.log("newInfo=", newInfo);
		userInfo = newInfo;
		console.log("ad_id=", userInfo.ad_id);
		console.log("clickid=", userInfo.clickid);

		//添加金豆收支明细
		const add_jindou = await db.collection('a_jindou_detail').add({
			user_id: orderinfo.user_id,
			nickname: orderinfo.nickname || "匿名",
			change_num: orderinfo.bean, //增加的金豆数量
			change_reason: "抖音支付" + parms_msg.total_amount + "分钱充值" + orderinfo.bean + "金豆",
			type: "income", //类型：expend:支出,income:收入。
			_add_time: nowtime
		})

		//添加操作日志
		const addlog = await db.collection('a_log').add({
			user_id: orderinfo.user_id || '无',
			operator: "抖音支付回调云函数recharge",
			event: "支付" + parms_msg.total_amount + "分钱充值" + orderinfo.bean + "金豆",
			_add_time: nowtime
		})
	} else {

		let addtime = 0;
		//【开通会员】这个类型是为了兼容老版本的年费会员
		if (orderinfo.subject == "开通会员" && orderinfo.pay_status == 0) {
			addtime = 31536000000 //365天
		}
		if (orderinfo.subject == "年度会员" && orderinfo.pay_status == 0) {
			addtime = 31536000000 //365天
		}
		if (orderinfo.subject == "季度会员" && orderinfo.pay_status == 0) {
			addtime = 7776000000 //90天
		}
		if (orderinfo.subject == "月度会员" && orderinfo.pay_status == 0) {
			addtime = 2592000000 //30天
		}

		//先查询用户信息，是否已是会员
		const get_plus_expire_time = await db.collection('uni-id-users').doc(orderinfo.user_id).field({
			plus_expire_time: true
		}).get()
		var nowtime = new Date().getTime()
		const plus_expire = get_plus_expire_time.data[0].plus_expire_time
		if (plus_expire * 1 < nowtime * 1) {
			let date = new Date();
			let nextyear = date.setDate(new Date().getDate() + 365); //365天后的日期 console.log(date); 
			//如果会员已到期，会员时间就是当前时间+365天
			console.log("orderinfo.user_id", orderinfo.user_id);
			console.log("nextyear", nextyear);
			const updateUser = await db.collection('uni-id-users').doc(orderinfo.user_id).update({
				plus_type: 1,
				plus_expire_time: nextyear
			})
		} else {
			let nextyear2 = plus_expire + 31536000000
			console.log("74行", nextyear2);
			//如果会员没有到期，会员时间就是到期时间+365天
			const updateUser2 = await db.collection('uni-id-users').doc(orderinfo.user_id).update({
				plus_expire_time: nextyear2
			})
		}
		//添加操作日志
		const addlog2 = await db.collection('a_log').add({
			user_id: orderinfo.user_id || '无',
			operator: "抖音支付回调云函数recharge",
			event: "开通一年会员",
			_add_time: nowtime
		})

	}

	//修改充值记录订单，状态为已支付，并记录实付金额，微信支付订单号等
	const update_order = await db.collection('a_recharge').where({
		out_trade_no: parms_msg.cp_orderno
	}).update({
		shifu_amount: parms_msg.total_amount || 0,
		transaction_id: parms_msg.channel_no || "transaction_id",
		payment_order_no: parms_msg.payment_order_no || "payment_order_no",
		tt_order_id: parms_msg.order_id || "tt_order_id",
		pay_status: 1,
		settle: 0, //分账状态，0为未分账，1为已分账
		ad_id: userInfo.ad_id, //如果是来自巨量投流的用户，会在该用户信息里绑定ad_id
		clickid: userInfo.clickid, //如果是来自巨量投流的用户，会在该用户信息里绑定clickid，用于回传数据
		_add_time: nowtime
	})

	if (userInfo.clickid) {
		// 回传支付事件给巨量
		// 付费回传方式
		let jlurl = "https://ad.toutiao.com/track/activate/?callback=" + userInfo.clickid + "&event_type=2"
		let tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
			method: 'GET',
			data: {},
			contentType: 'json',
			dataType: 'json'
		})

		// 回传记录入库
		let addhc1 = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "tiktok",
			user_id: userInfo._id,
			out_trade_no: parms_msg.cp_orderno,
			invite_code: userInfo.invite_code,
			middleman_id: userInfo.middleman_id,
			tfid: userInfo.tfid,
			adid: userInfo.ad_id,
			clickid: userInfo.clickid,
			money: parms_msg.total_amount,
			result: tthuichuan_result.data,
			time: nowtime,
			remark: "抖音小程序用户支付回传记录"
		})
	}

	let res = {
		"err_no": 0,
		"err_tips": "success"
	}
	//返回数据给客户端
	return res
};